package org.example.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * [7.7] 使用异步设计思路改善BIO代码
 */
public class BioServer2 {

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 3, TimeUnit.MINUTES, null);

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket();
        // 绑定9090端口
        serverSocket.bind(new InetSocketAddress(9090));
        while (true) {
            // 阻塞接受外部连接
            Socket accept = serverSocket.accept();
            executor.execute(() -> {
                InputStream inputStream;
                while (true) {
                    try {
                        inputStream = accept.getInputStream();
                        byte[] bytes = new byte[10];
                        // 阻塞调用
                        inputStream.read(bytes);
                        System.out.println("服务器端接受的数据是：" + new String(bytes));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}
